
JQuery是JavaScript的一套函式庫,JQuery Ajax 提供了一組 Ajax 的方法讓我們可以做到非同步的HTTP請求,當中我們可以簡單的用 $.ajax(), $.get(), $.post() 等...。
其中 $.ajax() 是最基本最靈活的方法,允許我們進行各種設定和自定義請求。
JQuery為第三方函式庫,所以在使用前要先引入歐!
// 使用 $.ajax() 方法發送 GET 請求
$.ajax({
    url: 'https://api.example.com/data',
    type: 'GET',
    dataType: 'json',
    success: function(data) {
        console.log(data);
    },
    error: function(error) {
        console.error('Error:', error);
    }
});
// 使用 $.get() 方法,這是 $.ajax() 的簡化版,專門用於 GET 請求
$.get('https://api.example.com/data', function(data) {
    console.log(data);
});
// 使用 $.post() 方法發送 POST 請求
$.post('https://api.example.com/data', { key: 'value' }, function(data) {
    console.log(data);
}, 'json');
$.ajax(), $.get(), $.post() 等在2015 年後,大多數的主流瀏覽器開始實作並支援 Fetch API,它的設計基於 ES6 中的 Promise, 讓非同步操作更為簡單和直觀,當 Fetch API 完成請求後,開發者可以使用 then() 方法來處理伺服器的 response 進行後續操作,Fetch API 也是瀏覽器內建支援的語法,所以它不需要再額外引入函式庫,讓操作更加方便~
// 使用 Fetch API 發送 GET 請求
fetch('https://api.example.com/data')
    .then(response => {
        // 檢查回應是否成功
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();  // 解析回應為 JSON
    })
    .then(data => {
        console.log(data);  // 輸出解析後的資料
    })
    .catch(error => {
        console.error('Fetch error:', error);  // 輸出錯誤訊息
    });
// 使用 Fetch API 發送 POST 請求
fetch('https://api.example.com/data', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        key: 'value'
    })
})
.then(response => response.json())
.then(data => {
    console.log(data);
})
.catch(error => {
    console.error('Fetch error:', error);
});
特點:
.catch()方法便於捕捉錯誤async/await
缺點:
Axios是輕量化的函式庫,跟Fetch API 一樣是基於Promise的概念來設計,比較不同的是,Axios同時也支援在node.js中來使用,提供Fetch API缺少的某些功能(例如:Axios會自動轉換JSON()格式解析為JavaScript 物件、請求和回應的攔截,以及更好的錯誤處理機制)
// 首先,需要安裝 axios
import axios from 'axios';
axios.get('https://api.example.com/data')
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.error('Error:', error);
    });
特點:
promise和async/await
json()格式成為JavaScript的物件
參考文章
MDN-Fetch API
request的方式? ajax & fetch & axios
[Day 24] 動手篇 - 停!XMLHttpRequest or Fetch API